<template>
  <view class="address-container">
    <text v-if="loading">正在获取城市信息...</text>
    <text v-else-if="error">{{ error }}</text>
    <text v-else>您所在的城市是: {{ city }}</text>
  </view>
</template>

<script>
export default {
  name: "Address",
  components: {},
  props: {},
  data() {
    return {
      loading: true,
      error: null,
      city: "",
      // apiKey: "d9e69c9abc8db496b378c5bd79e2df4a",
      // apiKey: "7422003ec64a585ba4883751f3df80e6",
    };
  },
  mounted() {
    this.fetchCity();
  },
  methods: {
    fetchCity() {
      const url = `https://restapi.amap.com/v3/ip?key=${this.apiKey}`;

      uni.request({
        url: url,
        method: "GET",
        success: (res) => {
          console.log("请求成功：", res.data);
          if (res.data.status === "1" && res.data.info === "OK") {
            console.log(res.data.city);
            this.city = res.data.city;
          } else {
            this.error = `获取城市信息失败: ${res.data.info}`;
          }
        },
        fail: (err) => {
          console.log("请求失败：", err);
          this.error = `请求失败: ${err.errMsg}`;
        },
        complete: () => {
          this.loading = false;
        },
      });
    },
  },
};
</script>

<style scoped>
.address-container {
  padding: 20px;
  text-align: center;
}
</style>